package com.umeox.watch.moto.launcher.adapter;

import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.umeox.moto.common.utils.LanguageConfig;
import com.umeox.watch.moto.launcher.R;
import com.umeox.moto.watch.themes.LanguageBean;
import com.umeox.moto.watch.themes.ItemClickListener;

import java.util.List;
import java.util.Locale;


public class LanguageChooseAdapter extends RecyclerView.Adapter<LanguageChooseAdapter.ItemViewHolder> {

    private List<LanguageBean> list;

    private ItemClickListener itemClickListener;
    private int mSelectedPosition = -1;


    public LanguageChooseAdapter(List<LanguageBean> list, ItemClickListener itemClickListener) {
        this.list = list;
        this.itemClickListener = itemClickListener;
    }

    @NonNull
    @Override
    public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_language_choose, parent, false);

        return new ItemViewHolder(itemView);
    }

    public Locale getSelectedLanguage() {
        return list.get(Math.max(mSelectedPosition,0)).getLocale();
    }

    @Override
    public void onBindViewHolder(@NonNull ItemViewHolder holder, @SuppressLint("RecyclerView") int position) {

        final LanguageBean languageBean = list.get(position);

        holder.mRbt.setText(LanguageConfig.initialsToUpperCase(languageBean.getLocale()));
        final boolean selection = languageBean.isSelection();
        if (selection) {
            mSelectedPosition = position;
        }

        holder.mRbt.setSelected(selection);
        holder.itemView.setOnClickListener(v -> {
            if (mSelectedPosition == position) {
                return;
            }

            if (mSelectedPosition != -1) {
                final LanguageBean lastSelectedLanguage = list.get(mSelectedPosition);
                lastSelectedLanguage.setSelection(false);

            }

            mSelectedPosition = position;
            list.get(mSelectedPosition).setSelection(true);

            notifyDataSetChanged();
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    class ItemViewHolder extends RecyclerView.ViewHolder {
        private TextView mRbt;


        public ItemViewHolder(View itemView) {
            super(itemView);
            mRbt = itemView.findViewById(R.id.rb_language);

        }
    }
}

